package com.lms.servlet.user;

import com.alibaba.fastjson.JSONArray;
import com.lms.service.update.UploadService;
import com.lms.service.update.UploadServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class UploadServlet extends HttpServlet {
    private UploadService uploadService= new UploadServiceImpl();
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        this.doPost(request, response);
    }

    public synchronized void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HashMap<String, Object> map = new HashMap<>();
        String fileName = uploadService.saveFile(request, response);
        if (fileName!=null) {
            uploadService.excel(fileName);
            map.put("code",0);//上传文件解析成功
            response.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
            response.setContentType("text/json; charset=UTF-8");
        }else {
            map.put("code",500);//上传文件解析失败
            response.getOutputStream().write(JSONArray.toJSONString(map).getBytes("UTF-8"));
            response.setContentType("text/json; charset=UTF-8");
        }
    }
}
